/**
 * Copyright (C) 2025 pony working team
 * SPDX-License-Identifier: MulanPSL-2.0
 */

/* define to prevent recursive inclusion -------------------------------------*/
#ifndef __PONY_X_MAGIC_H__
#define __PONY_X_MAGIC_H__

/* includes (standard library, system) ---------------------------------------*/
#include <stdint.h>
/* includes (other library) --------------------------------------------------*/
/* includes (project) --------------------------------------------------------*/
/* includes (local) ----------------------------------------------------------*/

#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */

/* defines -------------------------------------------------------------------*/

#define X_MAGIC_INVALID_ID (uintptr_t)0xffffffffU

typedef struct x_magic {
    uintptr_t magic;
    uintptr_t id;
} x_magic_t;

#define x_magic_verify(p) (((uintptr_t)(p) != 0) && ((p)->magic == (uintptr_t)(p)))

#define x_magic_reset(p)                                                                           \
    do {                                                                                           \
        (p)->id = X_MAGIC_INVALID_ID;                                                              \
        (p)->magic = 0;                                                                            \
    } while (0)

#define x_magic_set(p, v)                                                                          \
    do {                                                                                           \
        (p)->id = (uintptr_t)(v);                                                                  \
        (p)->magic = (uintptr_t)(p);                                                               \
    } while (0)

#define x_magic_get(p) ((p)->id)

/* typedefs ------------------------------------------------------------------*/
/* macro ---------------------------------------------------------------------*/
/* inlines -------------------------------------------------------------------*/
/* externs -------------------------------------------------------------------*/

#ifdef __cplusplus
}
#endif /* __cplusplus */

#endif /* __PONY_X_MAGIC_H__ */
